package com.mjfeed.controller;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.mjfeed.Constants;
import com.mjfeed.entity.Area;
import com.mjfeed.service.AreaService;
import com.mjfeed.service.IndexImageService;
import com.mjfeed.service.ProductCategoryService;
import com.mjfeed.util.ValidateCode;

@Controller
public class CommonController extends BaseController {
	@Resource(name="areaService")
	private AreaService areaService;
	@Resource(name="productCategoryService")
	private ProductCategoryService productCategoryService;
	@Resource(name="indexImageService")
    private IndexImageService indexImageService;
	
	/**
	 * 生成验证码
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/validateCode")
	public void validateCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		String verifyCode = ValidateCode.generateTextCode(ValidateCode.TYPE_NUM_ONLY, 4, null);
		request.getSession().setAttribute("validateCode", verifyCode);
		response.setContentType("image/jpeg");
		BufferedImage bim = ValidateCode.generateImageCode(verifyCode, 90, 30, 3, true, Color.WHITE, Color.BLACK, null);
		ImageIO.write(bim, "JPEG", response.getOutputStream());
	}
	
	/**
	 * 地区
	 */
	@RequestMapping(value = "/area", method = RequestMethod.GET)
	public @ResponseBody Map<Long, String> area(Long parentId) {
		List<Area> areas = new ArrayList<Area>();
		if (parentId != null) {
			Area parent = areaService.getById(Area.class, parentId);
			if (parent != null) {
				areas = new ArrayList<Area>(parent.getChildren());
			}
		} else {
			areas = areaService.findRoots(null);
		}
		Map<Long, String> options = new HashMap<Long, String>();
		for (Area area : areas) {
			options.put(area.getId(), area.getName());
		}
		return options;
	}
	
	/**
	 * kindeditor文件上传
	 */
	@RequestMapping(value = "/kindeditor/upload", method = RequestMethod.POST)
	public String upload(@RequestParam(value="imgFile", required=true) MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> data = new HashMap<String, Object>();
		//文件保存目录路径
		String savePath = Constants.UPLOAD_PATH_PREFIX_KINDEDITOR;
		//文件保存目录URL
		String saveUrl  = getBasePath(request) + "download.shtml?filepath=" + Constants.UPLOAD_PATH_PREFIX_KINDEDITOR;
		//定义允许上传的文件扩展名
		HashMap<String, String> extMap = new HashMap<String, String>();
		extMap.put("image", "gif,jpg,jpeg,png,bmp");
		extMap.put("flash", "swf,flv");
		extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
//		extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

		//最大文件大小   20M           
		long maxSize = 20485760;
		String dirName = request.getParameter("dir");
		if (dirName == null) {
			dirName = "image";
		}
		if(!extMap.containsKey(dirName)){
			data.put("error", 1);
	    	data.put("message", "目录名不正确。");
	    	super.renderJson(response, data);
			return null;
		}
		//创建文件夹
		savePath += dirName + "/";
		saveUrl += dirName + "/";
		File saveDirFile = new File(savePath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String ymd = sdf.format(new Date());
		savePath += ymd + "/";
		saveUrl += ymd + "/";
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		String fileName = multipartFile.getOriginalFilename();
		long fileSize = multipartFile.getSize();
		//检查文件大小
		if(fileSize > maxSize){
			data.put("error", 1);
	    	data.put("message", "上传文件大小超过限制。");
	    	super.renderJson(response, data);
			return null;
		}
		//检查扩展名
		String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
		if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
			data.put("error", 1);
	    	data.put("message", "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
	    	super.renderJson(response, data);
			return null;
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
		File uploadedFile = new File(savePath, newFileName);
		try {
			multipartFile.transferTo(uploadedFile);
		} catch (Exception e) {
			e.printStackTrace();
			data.put("error", 1);
	    	data.put("message", "上传文件失败。");
	    	super.renderJson(response, data);
			return null;
		}
		data.put("error", 0);
		data.put("url", saveUrl + newFileName);
		super.renderJson(response, data);
		return null;
	}
	
	/**
	 * 文件下载
	 */
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public void download(@RequestParam(value="filepath", required=true) String filepath, HttpServletRequest request, HttpServletResponse response) {
		File file = new File(Constants.getRealFilePath(filepath));
		if (file.exists()) {
			String fileExtension = FilenameUtils.getExtension(file.getName());
			if (Constants.UPLOAD_IMAGE_EXTENSION.indexOf(fileExtension.toLowerCase()) > -1) {
				response.setContentType("image/jpeg");
			} else {
				response.setContentType("application/octet-stream;charset="+Constants.DEFAULT_ENCODING);
				response.setHeader("Content-Disposition", new StringBuffer("attachment;filename=").append(file.getName()).toString());	
			}
			try {
				OutputStream out = response.getOutputStream();
				out.write(FileUtils.readFileToByteArray(file));
				out.flush();
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 首页
	 */
	@RequestMapping(value = "/index", method=RequestMethod.GET)
	public String index(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setAttribute("productCategoryTree", productCategoryService.findTree());
		request.setAttribute("indexImages", indexImageService.getAllIndexImage());
		return "index";
	}
	
	/**
	 * 技术
	 */
	@RequestMapping(value = "/jishu", method=RequestMethod.GET)
	public String jishu(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setAttribute("productCategoryTree", productCategoryService.findTree());
		return "jishu";
	}
	
	/**
	 * 服务
	 */
	@RequestMapping(value = "/fuwu", method=RequestMethod.GET)
	public String fuwu(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setAttribute("productCategoryTree", productCategoryService.findTree());
		return "fuwu";
	}
	
	/**
	 * app
	 */
	@RequestMapping(value = "/app", method=RequestMethod.GET)
	public String app(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setAttribute("productCategoryTree", productCategoryService.findTree());
		return "app";
	}
}
